<script>
// 工作区
import Guide from './toolbar/GuideNewCard';
import Share from './toolbar/Share';
import WorkSpaceQuery from '../../mixins/WorkspaceQuery';
import WorkSpaceContent from './WorkSpaceContent';

import { uuid } from '@ktw/ktools';
import * as types from '../../store/types';
import * as utils from '../../utils/helps';
import { componentManager } from '../../utils/componentManager.js';

export default {
  name: 'WorkSpace',
  components: {
    Guide,
    Share,
    WorkSpaceContent,
  },
  mixins: [WorkSpaceQuery],
  data() {
    return {
      isCollapsed: false,
      newApp: false,
      setApp: false,
      delApp: false,
      shareApp: false,
      selectedItem: false,
      newLayout: {},
      layout: [],
      setAppName: '',
      setAppDescription: '',
      spinShow: true,
    };
  },
  computed: {
    layoutList() {
      return utils.setAllControlToArr(this.$store.getters.controls);
    },
    appData() {
      return this.$store.state.app.appData;
    },
    isAppSave() {
      return this.$store.state.app.isAppSave;
    },
  },
  watch: {
    layoutList(newVal) {
      this.layout = [];
      if (newVal.length !== 0 && this.layout.length === 0) {
        this.layout = newVal;
        window.dispatchEvent(new Event('resize'));
      }
    },
  },
  beforeMount() {
    // if (Object.keys(this.$store.getters.allControl).length === 0) {
    this.getLastAppData();
    // }
    this.$router.push('/workspace/' + this.$store.state.app.appData.id);
  },
  events: {
    'on-showSpin': 'showSpin',
  },
  // 判断应用的保存状态
  // beforeRouteLeave(to, from, next) {
  //   if (!this.isAppSave) {
  //     this.$Modal.confirm({
  //       title: '提示',
  //       content: '是否保存当前应用？',
  //       onOk: () => {
  //         this.isSaveApp(next);
  //         next();
  //       },
  //     });
  //   } else {
  //     next();
  //   }
  // },
  // beforeRouteLeave(to, from, next) {
  //   const maps = utils.findComponentsDownward(this, 'BaseMap');
  //   maps.forEach(item => {
  //     if (this.$store.state[item.mapId]) {
  //       this.$store.unregisterModule(item.mapId);
  //     }
  //     item.$mapObject.remove();
  //   });
  //   next();
  // },
  methods: {
    // 新增组件
    addElement(e) {
      // 生成组件唯一id
      let onlyId = uuid(20);
      // 判断新增组件的位置
      const pos = this.computedItemPos();
      this.newLayout = componentManager(e, onlyId, pos, this.layout.length);
      // 向store提交新增的组件数据
      this.$store.commit(types.UPDATE_CHART_CONFIG, { data: { [onlyId]: this.newLayout } });
      this.$store.commit(types.UPDATA_APPLY_CURRENTID, onlyId);
      // 更新应用
      this.upDataApp();
      this.setPath(e, onlyId);
      window.dispatchEvent(new Event('resize'));
    },
    // 新增组件的跳转方式
    setPath(e, onlyId) {
      const jump = {
        basicChart() {
          this.$router.push('/workspace/chartedit/' + onlyId + '/' + e.resId);
        },
        mapItem() {
          if (e.relEleType === 'mapItem') {
            this.$router.push('/workspace/mapedit/' + onlyId);
          } else if (e.relEleType === 'overlapMap') {
            this.$router.push('/workspace/overlapmapedit/' + onlyId);
          }
        },
        textItem() {
          this.layout.push(this.newLayout);
        },
        imgItem() {
          this.layout.push(this.newLayout);
        },
        frameItem() {
          this.layout.push(this.newLayout);
        },
        formItem() {
          this.$router.push('/workspace/formedit/' + onlyId + '/' + e.resId);
        },
        externalApp() {
          this.layout.push(this.newLayout);
        },
        templateApp() {
          this.$router.push('/workspace/appedit/' + onlyId);
        },
        customItem() {},
      };

      jump[e.eleType].call(this);
    },
    itemClick(name) {
      const state = {
        add() {
          this.newApp = true;
        },
        set() {
          this.setApp = true;
        },
        delete() {
          this.delApp = true;
        },
        share() {
          this.shareApp = true;
        },
        preview() {
          this.$router.push('/workspace/preview/' + this.appData.id);
          // 隐藏工具条
          this.$events.emit('on-hiddenTools', false);
        },
        // 保存
        save() {
          this.isSaveApp();
        },
      };
      state[name].call(this);
    },
    // 判断新增组件的位置
    computedItemPos() {
      let xP, yP;
      const allControls = Object.values(this.$store.getters.controls);
      allControls.sort(function(a, b) {
        return a.y - b.y;
      });
      if (allControls.length !== 0) {
        let lastComponentX = allControls[allControls.length - 1].appearance.position.x;
        let lastComponentY = allControls[allControls.length - 1].appearance.position.y;
        let lastComponentH = allControls[allControls.length - 1].appearance.position.h;
        let lastComponentW = allControls[allControls.length - 1].appearance.position.w;
        if (12 - (lastComponentX + lastComponentW) >= 2) {
          xP = lastComponentX + lastComponentW;
          yP = lastComponentY;
        } else {
          xP = 0;
          yP = lastComponentY + lastComponentH;
        }
        return { x: xP, y: yP };
      } else {
        return { x: 0, y: 0 };
      }
    },
    // 修改配置
    editAppConfig() {
      this.setApp = false;
      this.isUpDataApp(this.setAppName, this.setAppDescription);
    },
    // 更新应用
    upDataApp() {
      this.upDataAppConfig(
        {
          path: `${window.location.origin}/workspace/${this.appData.id}`,
          info: JSON.stringify(this.$store.getters.controls),
        },
        {
          id: this.appData.id,
        }
      );
    },
    //TODO: 删除应用
    isDeleteApp() {
      this.deleteApp(this.appData.id);
      this.$nextTick(() => {
        this.getLastAppData();
        this.delApp = false;
      });
    },
    // 保存应用
    isSaveApp() {
      new Promise((resolve, reject) => {
        const response = this.upDataAppConfig(
          {
            path: `${window.location.origin}/workspace/${this.appData.id}`,
            info: JSON.stringify(this.$store.getters.controls),
          },
          {
            id: this.appData.id,
          }
        );
        resolve(response);
      }).then(res => {
        this.$store.commit(types.UPDATE_APP_STATE);
        this.$Message.success('保存成功！');
      });
    },
    // 控制spin
    showSpin(status) {
      this.spinShow = status;
    },
  },
};
</script>
<template>
  <Layout class="datav-workspace">
    <Spin
      v-if="spinShow"
      fix>
      <loading type="ball-grid-pulse" />
    </Spin>
    <Sider
      ref="toolbar"
      :collapsed-width="80"
      width="80">
      <Menu
        active-name="1-2"
        theme="dark"
        width="auto"
        @on-select="itemClick">
        <MenuItem name="add">
        <Icon type="plus" />
        <span>新增</span>
        </MenuItem>
        <Modal
          v-model="newApp"
          class="vertical-center"
          class-name="vertical-center-modal"
          width="460">
          <Guide
            :is-get-data-sheet="newApp"
            @addNewElement="addElement"
            @closeGuide="newApp=false" />
          <div slot="footer" />
        </Modal>
        <MenuItem name="set">
        <Icon type="settings" />
        <span>设置</span>
        </MenuItem>
        <Modal
          v-model="setApp"
          class-name="vertical-center-modal"
          class="vertical-center"
          width="360"
          @on-ok="editAppConfig">
          <p slot="header">
            <span>设置</span>
          </p>
          <div style="text-align:left">
            <Row>
              <span>名称：</span>
            </Row>
            <Row>
              <Input v-model="setAppName"></Input>
            </Row>
            <Row>
              <span>描述：</span>
            </Row>
            <Row>
              <Input v-model="setAppDescription"></Input>
            </Row>
          </div>
        </Modal>
        <MenuItem name="save">
        <Icon type="checkmark"></Icon>
        <span>保存</span>
        </MenuItem>
        <MenuItem name="save-as">
        <Icon type="settings" />
        <span>另存为</span>
        </MenuItem>
        <MenuItem name="share">
        <Icon type="android-share-alt" />
        <span>共享</span>
        </MenuItem>
        <Modal
          v-model="shareApp"
          width="280"
          class="share-modal">
          <Share/>
        </Modal>
        <MenuItem name="delete">
        <Icon type="trash-a" />
        <span>删除</span>
        </MenuItem>
        <Modal
          v-model="delApp"
          class-name="vertical-center-modal"
          class="vertical-center"
          width="360"
          @on-ok="isDeleteApp">
          <p slot="header">
            <span>删除</span>
          </p>
          <div>
            <p> 该应用一旦删除,无法恢复，是否确定删除该应用？</p>
          </div>
        </Modal>
        <MenuItem name="preview">
        <Icon type="eye" />
        <span>预览</span>
        </MenuItem>
      </Menu>
    </Sider>
    <WorkSpaceContent @open-newchart="itemClick('add')"></WorkSpaceContent>
    <Sider
      v-if="selectedItem===true"
      v-model="isCollapsed"
      :collapsed-width="200"
      hide-trigger
      collapsible>
      <Tabs
        value="name1"
        style="color:#fff">
        <TabPane
          label="样式"
          name="name1">样式的内容</TabPane>
        <TabPane
          label="行为"
          name="name2">行为的内容</TabPane>
      </Tabs>
    </Sider>
  </Layout>
</template>


<style lang="less" scoped>
.datav-workspace {
  position: relative;
  .k-spin-fix {
    z-index: 901;
  }
}
.k-menu-item {
  padding: 8px 0;
  display: inline-block;
  width: 100%;
  text-align: center;
  border-radius: 10px;

  span {
    display: inline-block;
    vertical-align: bottom;
    width: 100%;
    text-overflow: ellipsis;
    white-space: nowrap;
    overflow: hidden;
    transition: width 0.2s ease 0.2s;
    font-size: 12px;
  }
  i {
    margin-right: 0;
    vertical-align: middle;
    transform: translateX(0px);
    transition: font-size 0.2s ease, transform 0.2s ease;
  }
}

.k-menu-item:hover {
  background-color: #449aee !important;
}

.k-layout.k-layout-has-sider {
  height: 100%;
}

.vertical-center /deep/ .vertical-center-modal {
  display: flex;
  align-items: center;
  justify-content: center;

  .k-modal {
    top: 0;

    .k-modal-footer {
      border: 0;
    }
  }
}

.layout-module {
  display: inline-block;
  border-radius: 4px;
  vertical-align: middle;
  height: 32px;

  .svgactive a:hover /deep/ .k-svgicon > svg {
    fill: #2d8cf0 !important;
  }

  a {
    cursor: pointer;
    vertical-align: middle;
  }
}

.share-modal /deep/ .k-modal-footer {
  display: none;
}
</style>
